package sisi.bank;

import java.util.List;

import javax.persistence.EntityManager;

/**
 * BankController.java - Controller class for the <i>bank database table</i>. 
 * @author Pedro Gonzalez pedro@sisisoftware.it
 * @author Claudio Pelosi claudio@sisisoftware.it
 * @author SISI Software S.n.c. - www.sisisoftware.it
 * @version 1.0, 02/10/2013
 * 
 */

public class BankController {

	private EntityManager getEntityManager() {
		return new sisi.MyEmf().getEntityManager();
	}

	public Bank[] getBank(String cerca) {
		List<Bank> banks = getBankList(cerca);
		return banks.toArray(new Bank[0]);
	}

	@SuppressWarnings("unchecked")
	public List<Bank> getBankList(String cerca) {

		String cWhere = "";
		if (cerca != null && !cerca.isEmpty()) {
			cWhere = " WHERE TRIM( BOTH FROM UPPER(c.bank) ) LIKE :cerca ";
		}

		EntityManager em = getEntityManager();
		try {
			javax.persistence.Query q = em
					.createQuery("select c from Bank as c " + cWhere
							+ " order by c.bank");
			
			if (cerca != null && !cerca.isEmpty()) {
				q.setParameter("cerca", '%'+cerca.trim().toUpperCase()+'%' );
			}
			
			List<Bank> ar1 = q.getResultList();
			return ar1;
		} finally {
			em.close();
		}
	}

	public Bank getBankxId(int id) {

		EntityManager em = getEntityManager();
		try {
			Bank bankx = em.find(Bank.class, id);
			return bankx;
		} finally {
			em.close();
		}
	}

	@SuppressWarnings("finally")
	public Bank addBank(Bank bank) {
		EntityManager em = getEntityManager();
		try {
			em.getTransaction().begin();
			em.persist(bank);
			em.getTransaction().commit();
			bank = refreshBank(bank);
		} finally {
			em.close();
			return bank;
		}
	}

	@SuppressWarnings("finally")
	public boolean updateBank(Bank bank) {

		EntityManager em = getEntityManager();
		try {
			em.getTransaction().begin();
			Bank bankx = em.find(Bank.class, bank.getId());
			bankx.setId(bank.getId());
			bankx.setAddress(bank.getAddress());
			bankx.setBank(bank.getBank());
			bankx.setCap(bank.getCap());
			bankx.setCceuro(bank.getCceuro());
			bankx.setCcusd(bank.getCcusd());
			bankx.setCity(bank.getCity());
			bankx.setIbaneur(bank.getIbaneur());
			bankx.setIbanusd(bank.getIbanusd());
			bankx.setSwft(bank.getSwft());
			em.getTransaction().commit();
			em.flush();

		} finally {
			em.close();
			return false;
		}
	}

	@SuppressWarnings("finally")
	public Bank refreshBank(Bank bank) {

		Bank bankx = bank;
		EntityManager em = getEntityManager();
		try {
			em.getTransaction().begin();
			bankx = em.find(Bank.class, bank.getId());
			em.flush();
			em.refresh(bankx);
		} finally {
			em.close();
			return bankx;
		}
	}

	@SuppressWarnings("finally")
	public boolean removeBank(Bank bank) {
		EntityManager em = getEntityManager();
		try {
			em.getTransaction().begin();
			Bank bankx = em.find(Bank.class, bank.getId());
			em.remove(bankx);
			em.getTransaction().commit();
		} finally {
			em.close();
			return false;
		}
	}

}
